package com.easycamera.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Rect
import android.util.Log


object BitmapUtils {
    val TAG = "BitmapUtils"
    /**
     * 合并两张图像
     */
    fun mergeBitmap(backBitmap: Bitmap?, frontBitmap: Bitmap?): Bitmap? {
        if (backBitmap == null || backBitmap.isRecycled
                || frontBitmap == null || frontBitmap.isRecycled) {
            Log.e(TAG, "backBitmap=$backBitmap;frontBitmap=$frontBitmap")
            return null
        }
        val tempBackBitmap = modifyBitmapSize(backBitmap, frontBitmap.width.toFloat(), frontBitmap.height.toFloat())
        tempBackBitmap?.let {
            val bitmap = tempBackBitmap.copy(Bitmap.Config.ARGB_8888, true)
            val canvas = Canvas(bitmap)
            val baseRect = Rect(0, 0, tempBackBitmap.width, tempBackBitmap.height)
            val frontRect = Rect(0, 0, tempBackBitmap.width, tempBackBitmap.height)
            canvas.drawBitmap(frontBitmap, frontRect, baseRect, null)
            return bitmap

        }

        return null

    }

    /**
     * 调整图片的大小
     */
    fun modifyBitmapSize(b: Bitmap, x: Float, y: Float): Bitmap? {
        val w = b.width
        val h = b.height
        val sx = x / w
        val sy = y / h
        val matrix = Matrix()
        matrix.postScale(sx, sy) // 长和宽放大缩小的比例
        return Bitmap.createBitmap(b, 0, 0, w,
                h, matrix, true)
    }

    fun rotaingImageView(angle: Int, bitmap: Bitmap): Bitmap? {
        var returnBm: Bitmap? = null
        // 根据旋转角度，生成旋转矩阵
        val matrix = Matrix()
        matrix.postRotate(angle.toFloat())
        try { // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        } catch (e: OutOfMemoryError) {
        }
        if (returnBm == null) {
            returnBm = bitmap
        }
        if (bitmap != returnBm) {
            bitmap.recycle()
        }
        return returnBm
    }


}